13. Adding hooks before/after saving and deleting
Django provides hooks for executing arbitrary code around save() and delete(). Just add any of the following methods to your model:
- _pre_save() is called before an object is saved.
- _post_save() is called after an object is saved.
- _pre_delete() is called before an object is deleted.
- _post_delete() is called after an object is deleted.
Model source code
from django.core import meta
class Person(meta.Model):
first_name = meta.CharField(maxlength=20)
last_name = meta.CharField(maxlength=20)
def __repr__(self):
return "%s %s" % (self.first_name, self.last_name)
def _pre_save(self):
print "Before save"
def _post_save(self):
print "After save"
def _pre_delete(self):
print "Before deletion"
def _post_delete(self):
print "After deletion"
API reference
Person objects have the following methods:
- delete()
- save()
Sample API usage
This sample code assumes the above model has been saved in a file examplemodel.py.
>>> from django.models.examplemodel import persons >>> p1 = persons.Person(first_name='John', last_name='Smith') >>> p1.save() Before save After save >>> persons.get_list() [John Smith] >>> p1.delete() Before deletion After deletion >>> persons.get_list() []
Comments
Dustin August 23, 2005 at 3:39 p.m.
Is there a way to tell whether the object was added or updated from a _post_save?
It doesn't look like there's an obvious way from reading the source, but I would like to (for example) send an email whenever a particular record is created, but not when the record is updated.
Clue September 6, 2005 at 1:42 a.m.
Dustin:
I'm not sure but you should check self.id value.
According to DB-API document, created new object will have id value of None.
stava October 8, 2005 at 5:54 p.m.
The example here really should show how to reach the values of the object being saved (e.g. _pre_save()), rather than some useless print-statements.
Post a comment
Note: Please only use the comments for questions/critcisms/suggestions on the docs; if you experience errors please file a ticket, ask in the IRC channel, or post to the django-users list. Comments will be periodically reviewed, integrated into the documentation proper, and removed.

Simon Willison August 10, 2005 at 10:17 a.m.
Is it possible to prevent a save or delete from happening at all in the _pre_save and _pre_delete methods?